<template>
  <div class="app-table">
    <p>{{ curState }}</p>
    <a-table :columns="columns" :data-source="data">
      <template v-slot:action="{ record }">
        <span>
          <a-button
            type="primary"
            @click="
              borrowVisible = !borrowVisible;
              borrowForm.officerId = record.id;
            "
            :disabled="record.remain <= 0"
            >借用</a-button
          >
          <a-modal
            title="借用麦克风"
            v-model:visible="borrowVisible"
            :confirm-loading="loading"
            @ok="borrow"
          >
            <a-form :model="borrowForm">
              <a-form-item label="借用人">{{ name }}</a-form-item>
              <a-form-item label="从何处借用">
                {{ record.name }}（工号：{{ record.id }}）
              </a-form-item>
              <a-form-item label="借用课程名">
                <a-input
                  v-model:value="borrowForm.lesson"
                  placeholder='例如："数据库系统原理"'
                />
              </a-form-item>
              <a-form-item label="借用地点">
                <a-input
                  v-model:value="borrowForm.classroom"
                  placeholder='例如："(一)304"'
                />
              </a-form-item>
            </a-form>
          </a-modal>
          <a-button
            type="primary"
            :disabled="!returnAvailable || record.remain >= record.max"
            @click="
              returnVisible = !returnVisible;
              returnOfficerId = record.id;
            "
            >归还</a-button
          >
          <a-modal
            title="归还麦克风"
            v-model:visible="returnVisible"
            :confirm-loading="loading"
            @ok="returnTo"
          >
            <a-descriptions title="借用人信息">
              <a-descriptions-item label="姓名">
                {{ returnForm.stuffRealName }}
              </a-descriptions-item>
              <a-descriptions-item label="学（工）号">
                {{ returnForm.stuffNum }}
              </a-descriptions-item>
              <a-descriptions-item label="学（书）院">
                {{ returnForm.college }}
              </a-descriptions-item>
              <a-descriptions-item label="课程名">
                {{ returnForm.lesson }}
              </a-descriptions-item>
              <a-descriptions-item label="教室">
                {{ returnForm.classroom }}
              </a-descriptions-item>
            </a-descriptions>
            你确定要将麦克风归还给{{ record.name }}（工号：{{ record.id }}）？
          </a-modal>
        </span>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref } from "vue";
import { BASE_URL, myPost, Response } from "@/utils/request";
import { useStore } from "vuex";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "BorrowTable",
  props: {
    url: {
      type: String,
      default: ""
    }
  },
  setup() {
    const data = ref([] as any[]);
    const store = useStore();
    const name = computed(() => store.getters.name);
    const curState = ref("");
    console.log(name);
    // const columns = computed(() => getColumns(data.value));
    const columns = [
      {
        dataIndex: "name",
        key: "name",
        title: "姓名"
      },
      {
        dataIndex: "id",
        key: "id",
        title: "工号"
      },
      {
        dataIndex: "remain",
        key: "remain",
        title: "剩余麦克风数量"
      },
      {
        dataIndex: "max",
        key: "max",
        title: "最大麦克风数量"
      },
      {
        key: "action",
        title: "操作",
        slots: { customRender: "action" }
      }
    ];

    const returnForm = reactive({
      stuffId: store.getters.id,
      officerId: 0,
      stuffRealName: "",
      stuffNum: "",
      college: "",
      lesson: "",
      classroom: ""
    });

    function getBorrowTable() {
      myPost(BASE_URL + "/stuff/queryOfficer", {}).then((resp: Response) => {
        data.value = (resp.data.data as any[]).map((item, key) => ({
          ...item,
          key
        }));
      });
    }

    const loading = ref(false);
    const borrowVisible = ref(false);
    const borrowForm = reactive({
      stuffId: store.getters.id,
      officerId: 0,
      lesson: "",
      classroom: ""
    });

    let respBody = {
      isSuccess: false,
      msg: "",
      data: []
    };

    function success() {
      loading.value = false;
      const msg = respBody["msg"];
      message.success({ content: msg, duration: 2 });
    }

    function error() {
      loading.value = false;
      const msg = respBody["msg"];
      message.error({ content: msg, duration: 2 });
    }

    function queryBorrow() {
      myPost(BASE_URL + "/stuff/queryBorrowFrom", {
        stuffId: store.getters.id
      }).then((resp: Response) => {
        respBody = resp.data;
        if (respBody["isSuccess"]) {
          curState.value = "当前您" + respBody["msg"];
          if (respBody.data.length > 0) {
            returnForm.stuffRealName = respBody.data[0]["stuffRealName"];
            returnForm.stuffNum = respBody.data[0]["stuffNum"];
            returnForm.college = respBody.data[0]["college"];
            returnForm.lesson = respBody.data[0]["lesson"];
            returnForm.classroom = respBody.data[0]["classroom"];
            store.commit("confirmBorrow");
          }
        } else {
          curState.value = "错误！";
          error();
        }
      });
    }

    function update() {
      getBorrowTable();
      queryBorrow();
    }

    function borrow() {
      loading.value = true;
      myPost(BASE_URL + "/stuff/borrow", borrowForm)
        .then((resp: Response) => {
          respBody = resp.data;
          if (respBody["isSuccess"]) {
            success();
            borrowVisible.value = false;
          } else {
            error();
          }
          update();
        })
        .catch((error: any) => {
          message.error({ content: error, duration: 2 });
        });
    }

    const returnAvailable = computed(() => store.getters.hasBorrow);
    const returnVisible = ref(false);
    const returnOfficerId = ref(0);

    function returnTo() {
      loading.value = true;
      myPost(BASE_URL + "/stuff/giveBack", {
        stuffId: store.getters.id,
        officerId: returnOfficerId.value
      })
        .then((resp: Response) => {
          respBody = resp.data;
          if (respBody["isSuccess"]) {
            success();
            store.commit("confirmReturn");
            returnVisible.value = false;
          } else {
            error();
          }
          update();
        })
        .catch((error: any) => {
          message.error({ content: error, duration: 2 });
        });
    }

    update();

    return {
      curState,
      columns,
      data,
      name,
      borrowVisible,
      borrowForm,
      borrow,
      loading,
      returnAvailable,
      returnVisible,
      returnForm,
      returnOfficerId,
      returnTo
    };
  }
});
</script>
<style scoped></style>
